package cn.pconline.autoclub.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.SubjectDyna;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.service.UserSubjectService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.WebUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * 话题动态 controller
 * @author fgs
 *
 */
@Controller
@RequestMapping("/subjectDyna")
public class SubjectDynaController {

	@Autowired
	private SubjectService subjectService;
	
	@Autowired
	private SubjectDynaService subjectDynaService;
	
	@Autowired
	private UserSubjectService userSubjectService;
	
	@Autowired
	private UserService userService;
	
    @Autowired
    private UserAuth userAuth;
    
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private DynaService dynaService;
	
	private static Logger log = LoggerFactory.getLogger(SubjectDynaController.class);
	/**每页最多条数**/
	private static final int MAX_PAGE_SIZE = 100;
	
	private static final int DEFAULT_PAGE_SIZE = 30;
	/**
	 * 话题详细页面跳转
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value = "/detail.do", method = RequestMethod.GET)
	public String detailSubject(HttpServletRequest req, HttpServletResponse resp){
		long subjectId = WebUtils.paramLong( req, "subjectId", 0);
		int orderType = WebUtils.paramInt(req, "order", SubjectDyna.ORDER_BY_NEW );
		int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", DEFAULT_PAGE_SIZE, 1, MAX_PAGE_SIZE);
        Subject subject = subjectService.findSubjectById(subjectId);
        
        if(subject==null){
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        String createName = userService.getNickNameByUserId( subject.getCreateBy() );
        User user = userAuth.getUser(req, resp);
        
        /**置顶动态**/
        List<DynaInfo> topDynaList = subjectDynaService.listDynaByTop(subjectId);
        
        Pager<DynaInfo> pagerDyna = null;
        /**最新”和“最热” 显示内容 ，不包括置顶数据**/
        if(orderType==SubjectDyna.ORDER_BY_NEW){
        	pagerDyna = subjectDynaService.pageDynaBySubjectIdOrderNew( subjectId, pageNo, pageSize, Subject.TOP_NO);
        	req.setAttribute("type", subjectId);
        }else if(orderType == SubjectDyna.ORDER_BY_HOT){
        	pagerDyna = subjectDynaService.pageDynaBySubjectIdOrderReply( subjectId, pageNo, pageSize, Subject.TOP_NO);
        	req.setAttribute("type", subjectId+"/hot");
        }
       req.setAttribute("NEW", SubjectDyna.ORDER_BY_NEW);
       req.setAttribute("HOT", SubjectDyna.ORDER_BY_HOT);
       req.setAttribute("orderType", orderType );
       if(pagerDyna!=null){
    	   req.setAttribute("ids", getDynaInfoIds(pagerDyna.getResultList(),topDynaList));  
       }
       
       //超级管理员
       long supperMan = systemConfig.getSubjectSupperMan();
       boolean isSupperMan = user.getUid() == supperMan;
       boolean isCreator = user.getUid()==subject.getCreateBy();
       //过滤导语换行
       subject.setIntroduction(subjectService.filterContent(subject.getIntroduction()));
       req.setAttribute("topDynaList", topDynaList );
       req.setAttribute("pageSize", pageSize);
       req.setAttribute("isLogin", user.getUid() >0 );
       req.setAttribute("isCreator", (isSupperMan || isCreator));
       req.setAttribute("user", user);
       req.setAttribute("createName", createName );
       req.setAttribute("pager", pagerDyna);
       req.setAttribute("subject", subject );
       req.setAttribute("TOP_YES", Subject.TOP_YES );
       req.setAttribute("TOP_NO",Subject.TOP_NO);
       
       return "template/subject/subject_detail";
	}
	
	private String getDynaInfoIds(List<DynaInfo> list,List<DynaInfo> topList){
		if(list==null) return "";
		String idsStr = "";
		for(DynaInfo dynaInfo:list){
			idsStr +=dynaInfo.getDynaInfoId()+",";
		}
		for(DynaInfo topDyna:topList) {
			idsStr +=topDyna.getDynaInfoId()+",";
        }
		return idsStr;
	}
	
	/**
	 * 删除话题动态
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/deleteSubjectDyna.do", method = RequestMethod.POST)
	public void deleteSubjectDyna(HttpServletRequest request, HttpServletResponse response){
		WebUtils.setEncoding(request, response);
		String callback = WebUtils.param(request, "callback", "");
		long subjectId = WebUtils.paramLong( request, "subjectId", 0);
		long dynaInfoId = WebUtils.paramLong( request, "dynaInfoId", 0);
		long createBy = WebUtils.paramLong( request, "createBy", 0);
		Subject subject = subjectService.findSubjectById(subjectId);
		if(subject==null){
			AppUtils.printErrorMsg(response,"操作失败，话题不存在", callback);
        	return;
        }
		User user = userAuth.getUser(request, response);//验证用户是否登录
        if(user.getUid()!=subject.getCreateBy()){
        	AppUtils.printErrorMsg(response,"操作失败，没有权限", callback);
        	return;
        }
        SubjectDyna subjectDyna = subjectDynaService.findSubjectDynaById(subjectId, dynaInfoId);
        if(subjectDyna != null){
        	   //删除话题动态同时减去话题相应的讨论数    话题的讨论数 = 话题动态数+话题动态回复数 
        	  subject.setReplyCount(subject.getReplyCount()-subjectDyna.getPostCount());
        }
        subjectDynaService.deleteSubjectDyna( subjectId, dynaInfoId );
        userSubjectService.deleteUserSubject( createBy, subjectId, dynaInfoId );
        subject.setReplyCount(subject.getReplyCount()-1);
        subjectService.updateByField( subject, "reply_count" );
        AppUtils.printSuccessMsg( response, "删除成功", null, callback );
		
	}
	
	/**
	 * 置顶（取消置顶）
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/setTop.do", method = RequestMethod.POST)
	public void setTop(HttpServletRequest request, HttpServletResponse response){
		WebUtils.setEncoding(request, response);
		String callback = WebUtils.param(request, "callback", "");
		long subjectId = WebUtils.paramLong( request, "subjectId", 0);
		long dynaInfoId = WebUtils.paramLong( request, "dynaInfoId", 0);
		long createBy = WebUtils.paramLong( request, "createBy", 0);
		int type = WebUtils.paramInt( request, "type", Subject.TOP_NO);
		Subject subject = subjectService.findSubjectById(subjectId);
		if(subject==null){
			AppUtils.printErrorMsg(response,"操作失败，话题不存在", callback);
        	return;
        }
		User user = userAuth.getUser(request, response);//验证用户是否登录
        if(user.getUid()!=subject.getCreateBy()){
        	AppUtils.printErrorMsg(response,"操作失败，没有权限", callback);
        	return;
        }
        subjectDynaService.updateTop( subjectId, dynaInfoId, type );
        userSubjectService.updateTop( createBy, subjectId, dynaInfoId, type );
        AppUtils.printSuccessMsg( response, "操作成功", null, callback );
	}
}
